﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using Zone;


namespace 检测邮件服务器有效性
{

    public partial class Form1 : BaseForm
    {
        HandleForEach hfe = new HandleForEach();
        int i_fail = 0;
        public Form1()
        {
            InitializeComponent();
        }

        int GetWeiMiao()
        {
            int weimiao = 100;
            try
            {
                weimiao = int.Parse(textBox4.Text.Trim());
            }
            catch 
            {

            }
            return weimiao;
        }                       
        private void button3_Click(object sender, EventArgs e)
        {
            string FaXinDiZhi = textBox1.Text.Trim();
            string user = textBox2.Text.Trim();
            string pwd = textBox3.Text.Trim();
            string ems = richTextBox3.Text.Trim();

        }
        /// <summary>
        /// 让字符串对齐
        /// </summary>
        /// <returns></returns>
        string eqString(string str)
        {                        
            for(int i = 0;i<1000;i++)
            {
                str += " ";
                if (str.Length == 50) break;
            }
            return str;
            
        }
        void CheckEmailServer(string s, int idex)
        {
            string smv = getMailServer(s);
            richTextBox1.Text += eqString(s) + "--> " + smv + "\n";
            this.richTextBox1.Focus();
            this.richTextBox1.Select(this.richTextBox1.TextLength, 0);
            this.richTextBox1.ScrollToCaret();
            if (smv.Contains("无效"))
            {
                richTextBox2.AppendText(s + "\n");
                i_fail++;
            }
            label1.Text = idex + 1 + "/" + (hfe.ArrEmails().Length).ToString() + "(进度)";
            label2.Text = i_fail + "/" + (hfe.ArrEmails().Length).ToString() + "(无效域名/总数)";
        }
        void CheckEmailAdd(string s, int idex)
        {
            string sError = "";
            string smv = checkEmail(s,out sError).ToString();
            richTextBox1.Text += s + "\t\t\t\t\t--> " + smv + "\n";
            if (smv !="200")
            {
                richTextBox2.Text += s + " \t--> " + sError + "\n";
                i_fail++;
            }
            label1.Text = idex + 1 + "/" + (hfe.ArrEmails().Length).ToString() + "(进度)";
            label2.Text = i_fail + "/" + (hfe.ArrEmails().Length).ToString() + "(无效域名/总数)";
        }
        void CheckRepeatItem(string s, int idex)
        {
            string s3 = s.Substring(s.IndexOf('@'), s.Length - s.IndexOf('@'));
           
            if (!richTextBox1.Text.Contains(s3))
            {
                richTextBox1.AppendText(s + "\n");
                i_fail++;
            }
            label1.Text = i_fail + "/" + (hfe.ArrEmails().Length).ToString() + "(非重/总数)";
        }

        public string getMailServer(string strEmail)
        {
            if (string.IsNullOrEmpty(strEmail)) return "";
            if (!strEmail.Contains("@")) return "";
            string strDomain = strEmail.Split('@')[1];
            ProcessStartInfo info = new ProcessStartInfo();
            info.UseShellExecute = false;
            info.RedirectStandardInput = true;
            info.RedirectStandardOutput = true;
            info.FileName = "nslookup";
            info.CreateNoWindow = true;
            info.Arguments = "-type=mx " + strDomain;
            Process ns = Process.Start(info);
            StreamReader sout = ns.StandardOutput;
            Regex reg = new Regex("mail exchanger = (?<mailServer>[^\\s].*)");
            string strResponse = "";
            while ((strResponse = sout.ReadLine()) != null)
            {
                Match amatch = reg.Match(strResponse);
                if (reg.Match(strResponse).Success) return amatch.Groups["mailServer"].Value;
            }
            return "无效";
        }
        public int checkEmail(string mailAddress, out string errorInfo)
        {
            Regex reg = new Regex("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
            if (!reg.IsMatch(mailAddress))
            {
                errorInfo = "Email Format error!";
                return 405;

            }
            string mailServer = getMailServer(mailAddress);
            if (mailServer == null)
            {
                errorInfo = "Email Server error!";
                return 404;
            }
            TcpClient tcpc = new TcpClient();
            tcpc.NoDelay = true;
            tcpc.ReceiveTimeout = 3000;
            tcpc.SendTimeout = 3000;
            try
            {
                tcpc.Connect(mailServer, 25);
                NetworkStream s = tcpc.GetStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                StreamWriter sw = new StreamWriter(s, Encoding.Default);
                string strResponse = "";
                string strTestFrom = mailAddress;
                sw.WriteLine("helo " + mailServer);
                sw.WriteLine("mail from:<" + mailAddress + ">");
                sw.WriteLine("rcpt to:<" + strTestFrom + ">");
                strResponse = sr.ReadLine();
                if (!strResponse.StartsWith("2"))
                {
                    errorInfo = "UserName error!";
                    return 403;
                }
                sw.WriteLine("quit");
                errorInfo = String.Empty;
                return 200;

            }
            catch (Exception ee)
            {
                errorInfo = ee.Message.ToString();
                return 403;
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            hfe.ForEachPart(1, CheckEmailServer, StopTime);
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            hfe.ForEachPart(1, CheckEmailAdd, StopTime);
        }      

        void StopTime()
        {
            timer1.Enabled = false;
            timer2.Enabled = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            string s1 = richTextBox1.Text.Trim();
            richTextBox1.Text = ""; richTextBox2.Text = "";
            hfe.Emails = s1;
            i_fail = 0;
            hfe.ForEachAll(CheckRepeatItem);
        }           
        private void AllButtion_Click(object sender, EventArgs e)
        {
            Button bt = sender as Button;
            string btText = bt.Text;


            string s1 = richTextBox1.Text.Trim();
            string s2 = richTextBox2.Text.Trim();

            if (btText == "停止")
            {
                hfe.StopFor();
            }


            if (btText == "检测域名" || btText == "检测用户")
            {
                richTextBox1.Text = ""; richTextBox2.Text = "";
                i_fail = 0;

                hfe.Emails = s1;
                if (btText == "检测域名")
                {
                    timer1.Enabled = true;
                    timer1.Interval = GetWeiMiao();
                }
                if (btText == "检测用户")
                {
                    timer2.Enabled = true;
                    timer2.Interval = 800;
                }
              
            }

            if (btText == "清理")
            {
                s1= s1.Replace(" ","").Replace("-","").Replace(">","");
                richTextBox1.Text = s1;
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            base.Initialize();
        }
    }
}
